/**
 * @author mkosovan
 */


(function($){
	
	Backbone.sync = function(method, model, success, error){
		success();
	}
	
	var Item = Backbone.Model.extend({
		defaults: {
			part1: "Hello",
			part2: "World"
		}
	})
	
	var List = Backbone.Collection.extend({
		model:Item
	})
	
	var ItemView = Backbone.View.extend({
		tagName: 'li',
		
		events: {
			'click span.swap': 'swap',
			'click span.delete': 'remove'
		},
		
		initialize: function(){
			_.bindAll(this, 'render', 'unrender', 'swap', 'remove');
			
			this.model.bind('change', this.render);
			this.model.bind('remove', this.unrender);
		},
		
		render: function(){
			$(this.el).html(this.model.get('part1') + ' ' + this.model.get('part2') + ' ' + '<span style="font-family:sans-serif; color:blue; cursor:pointer;" class="swap">[swap]</span><span style="font-family:sans-serif; color:blue; cursor:pointer;" class="delete">[delete]</span>');
			
			return this;
		},
		
		unrender: function(){			
			$(this.el).remove();
		},
		
		swap: function(){
			
			this.model.set({
				'part1': this.model.get('part2'),
				'part2': this.model.get('part1')
			});
		},
		
		remove: function(){
		
			this.model.destroy();
		}
		
	});

	var ListView = Backbone.View.extend({
	el: $('body'),
	
	events: {
		'click button#add': 'addItem'
	},
	
	initialize: function () {
	  _.bindAll(this, 'render', 'addItem');
	  
	  this.collection = new List();
	  this.collection.bind('add', this.appendItem);
	  
	  this.counter = 0;
	  this.render();
	},
	
	render: function(){
		
		var self = this;
		
		$(this.el).append("<button id='add'>Add Item</button>");
		$(this.el).append("<ul></ul>");
		
		_(this.collection.models).each(function(item){
			self.appendItem(item);
		}, this)
	},
	
	addItem: function(){
		this.counter++;
		
		var item = new Item();
		item.set({
			part2: item.get('part2') + this.counter
		});
		this.collection.add(item);
	},
	
	appendItem: function(item){
		
		var itemView = new ItemView({
			model: item
		});
		
		$('ul').append(itemView.render().el);
	}
});

var listView = new ListView();	
	
})(jQuery);
